import { useRef, useEffect, useState } from 'react';
import {
  Card, Statistic, Table, Button,
  Avatar, Space, Row, Col, List, Tag, Skeleton, Typography,
  Badge, Divider, message, // 新增message组件用于操作反馈
  Modal
} from 'antd';
import {
  CalendarOutlined, DollarOutlined, UserAddOutlined,
  ArrowUpOutlined, ArrowDownOutlined,
  PlusCircleOutlined, FileTextOutlined, BellOutlined,
  BarChartOutlined, MessageOutlined
} from '@ant-design/icons';
import * as echarts from 'echarts';
import { useSelector } from 'react-redux';
import AddProduct from '../../component/product/AddProduct';
import { AddArrange } from '../../component/arrange/AddArrange';
import { AddEmployee } from '../../component/organization/AddEmployee';

const { Title, Text } = Typography;

export const Home = () => {
  const [isShow, set_isShow] = useState(true);
  const [chartsInitialized, setChartsInitialized] = useState(false);
  const revenueChartRef = useRef(null);
  const serviceChartRef = useRef(null);
  const { user } = useSelector(d => d.login);

  //新增产品模态框
  const [isAddProductModal, setIsAddProductModal] = useState(false);
  //设置排班
  const [isArrangeModal, setIsArrangeModal] = useState(false);
  //新增员工
  const [isAddEmployeeModal, setIsAddEmployeeModal] = useState(false);
  //数据看板


  // 模拟数据
  const revenueData = [8500, 9200, 7800, 10500, 11200, 14800, 12580];
  const serviceData = [
    { value: 35, name: '推拿按摩', itemStyle: { color: '#8B5A2B' } },
    { value: 25, name: '针灸治疗', itemStyle: { color: '#2F4F4F' } },
    { value: 20, name: '艾灸养生', itemStyle: { color: '#CD5C5C' } },
    { value: 15, name: '拔罐疗法', itemStyle: { color: '#22c55e' } },
    { value: 5, name: '中药熏蒸', itemStyle: { color: '#a855f7' } }
  ];

  // ====================== 快捷操作点击方法 ======================
  /**
   * 新增产品点击事件
   * 逻辑：可跳转至产品新增页面或打开新增弹窗
   */
  const handleAddProduct = () => {
    setIsAddProductModal(true);
  };

  /**
   * 新增排班点击事件
   * 逻辑：跳转至排班管理页面或打开排班弹窗
   */
  const handleAddSchedule = () => {
    setIsArrangeModal(true);
  };

  /**
   * 新增员工点击事件
   * 逻辑：跳转至员工管理-新增页面
   */
  const handleAddStaff = () => {
   setIsAddEmployeeModal(true);
  };

  /**
   * 数据看板点击事件
   * 逻辑：跳转至数据可视化看板页面
   */
  const handleOpenDashboard = () => {
    console.log('触发【数据看板】操作，当前操作用户：', user?.name);

    // 实际项目中可添加路由跳转：history.push('/dashboard/analysis')
  };

  // 快速操作配置（绑定对应点击方法）
  const quickActions = [
    {
      icon: <PlusCircleOutlined />,
      label: '新增产品',
      color: '#8B5A2B',
      onClick: handleAddProduct // 绑定新增产品方法
    },
    {
      icon: <UserAddOutlined />,
      label: '新增排班',
      color: '#2F4F4F',
      onClick: handleAddSchedule // 绑定新增排班方法
    },
    {
      icon: <FileTextOutlined />,
      label: '新增员工',
      color: '#CD5C5C',
      onClick: handleAddStaff // 绑定新增员工方法
    },
    {
      icon: <BarChartOutlined />,
      label: '数据看板',
      color: '#a855f7',
      onClick: handleOpenDashboard // 绑定数据看板方法
    }
  ];

  // ====================== 图表相关逻辑 ======================
  const initCharts = () => {
    const revenueChartEl = document.getElementById('revenue-chart');
    const serviceChartEl = document.getElementById('service-chart');

    if (!revenueChartEl || !serviceChartEl) {
      setTimeout(initCharts, 100);
      return;
    }

    if (revenueChartRef.current) revenueChartRef.current.dispose();
    if (serviceChartRef.current) serviceChartRef.current.dispose();

    revenueChartRef.current = echarts.init(revenueChartEl);
    serviceChartRef.current = echarts.init(serviceChartEl);

    updateAllCharts();
    setChartsInitialized(true);
  };

  const updateAllCharts = () => {
    updateRevenueChart();
    updateServiceChart();
  };

  const updateRevenueChart = () => {
    if (!revenueChartRef.current) return;

    const option = {
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: { color: '#333' },
        formatter: '{b}: ¥{c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisLine: { lineStyle: { color: '#eee' } }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        splitLine: { lineStyle: { color: '#f0f0f0' } }
      },
      series: [
        {
          data: revenueData,
          type: 'line',
          smooth: true,
          lineStyle: { width: 3, color: '#8B5A2B' },
          itemStyle: { color: '#8B5A2B' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(139, 90, 43, 0.3)' },
                { offset: 1, color: 'rgba(139, 90, 43, 0)' }
              ]
            }
          }
        }
      ]
    };

    revenueChartRef.current.setOption(option);
  };

  const updateServiceChart = () => {
    if (!serviceChartRef.current) return;

    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}%'
      },
      series: [
        {
          name: '理疗项目',
          type: 'pie',
          radius: ['70%', '90%'],
          avoidLabelOverlap: false,
          itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
          label: { show: false, position: 'center' },
          emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } },
          labelLine: { show: false },
          data: serviceData
        }
      ]
    };

    serviceChartRef.current.setOption(option);
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      set_isShow(false);
      initCharts();

      const handleResize = () => {
        revenueChartRef.current?.resize();
        serviceChartRef.current?.resize();
      };

      window.addEventListener('resize', handleResize);

      return () => {
        window.removeEventListener('resize', handleResize);
        revenueChartRef.current?.dispose();
        serviceChartRef.current?.dispose();
      };
    }, 1000);

    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    if (chartsInitialized) updateAllCharts();
  }, [chartsInitialized, revenueData, serviceData]);

  // ====================== 表格数据与配置 ======================
  const appointmentData = [
    {
      key: '1',
      customer: {
        name: '张晓明',
        id: '880012',
        avatar: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/ce160ec9525147a5aa085a44de7432d6.png~tplv-a9rns2rl98-24:720:720.png?rk3s=1fb89129&x-expires=1757555165&x-signature=9qfanl5eZhsJMnWKJv%2FljBL0KaM%3D'
      },
      service: '推拿按摩',
      doctor: '李员工',
      time: '09:30 - 10:30',
      status: 'completed'
    },
    {
      key: '2',
      customer: {
        name: '王丽',
        id: '880045',
        avatar: 'https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/c08a6d83f2364ea3a8954b9028b88b66.png~tplv-a9rns2rl98-24:720:720.png?rk3s=1fb89129&x-expires=1757560727&x-signature=%2BAt4muTDWOg2vAivzlSlsSEkk18%3D'
      },
      service: '针灸治疗',
      doctor: '陈员工',
      time: '11:00 - 12:00',
      status: 'inProgress'
    },
    {
      key: '3',
      customer: {
        name: '刘建国',
        id: '880078',
        avatar: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/82f7a7cce91040968026d2bec3be4aa5.png~tplv-a9rns2rl98-24:720:720.png?rk3s=1fb89129&x-expires=1757562514&x-signature=5N7QtOq8HHD06h5RTO3aE4Bbe7k%3D'
      },
      service: '艾灸养生',
      doctor: '赵员工',
      time: '14:00 - 15:00',
      status: 'pending'
    },
    {
      key: '4',
      customer: {
        name: '陈明',
        id: '880102',
        avatar: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/07658cbe9b2648e8835a362c2982c8d7.png~tplv-a9rns2rl98-24:720:720.png?rk3s=1fb89129&x-expires=1757562655&x-signature=1xTmyFxmVZVCBbR7YhxJ%2FtwtUSk%3D'
      },
      service: '拔罐疗法',
      doctor: '李员工',
      time: '16:30 - 17:30',
      status: 'scheduled'
    }
  ];

  const appointmentColumns = [
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
      width: 180,
      render: (customer) => (
        <Space size="small">
          <Avatar src={customer.avatar} size="small" />
          <div>
            <div style={{ fontWeight: 500 }}>{customer.name}</div>
            <div style={{ fontSize: 12, color: '#999' }}>卡号: {customer.id}</div>
          </div>
        </Space>
      )
    },
    {
      title: '理疗项目',
      dataIndex: 'service',
      key: 'service',
      width: 120
    },
    {
      title: '服务员工',
      dataIndex: 'doctor',
      key: 'doctor',
      width: 100
    },
    {
      title: '预约时间',
      dataIndex: 'time',
      key: 'time',
      width: 140
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => {
        const statusMap = {
          completed: { color: 'success', text: '已完成' },
          inProgress: { color: 'processing', text: '进行中' },
          pending: { color: 'warning', text: '待确认' },
          scheduled: { color: 'default', text: '已预约' }
        };
        const { color, text } = statusMap[status] || { color: 'default', text: '未知' };
        return <Badge status={color} text={text} />;
      }
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 140,
    //   fixed: 'right',
    //   render: () => (
    //     <Space size="small">
    //       <Text type="primary" style={{ cursor: 'pointer' }}>详情</Text>
    //       <Text style={{ cursor: 'pointer' }}>编辑</Text>
    //     </Space>
    //   )
    // }
  ];

  return (
    <div>


      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active style={{ padding: '20px 0' }} />
      ) : (
        <div>
          {/* 页面标题区 */}
          <div style={{ margin: '6px 10px 16px' }}>
            <Title level={2} style={{ color: '#2F4F4F', margin: 0 }}>控制台</Title>
            <Text type="secondary">欢迎回来，{user?.name || '管理员'}！这是今日的业务概览</Text>
          </div>

          {/* 1. 核心统计卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} lg={6}>
              <Card variant={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
                <Statistic
                  title="今日预约"
                  value={24}
                  valueStyle={{ color: '#8B5A2B' }}
                  prefix={<CalendarOutlined style={{ color: '#8B5A2B' }} />}
                  suffix={
                    <span style={{ color: '#52c41a', fontSize: 12, marginLeft: 8 }}>
                      <ArrowUpOutlined /> 较昨日 +3
                    </span>
                  }
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card variant={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
                <Statistic
                  title="今日收入"
                  value={12580}
                  valueStyle={{ color: '#2F4F4F' }}
                  prefix={<DollarOutlined style={{ color: '#2F4F4F' }} />}
                  suffix={
                    <span style={{ color: '#52c41a', fontSize: 12, marginLeft: 8 }}>
                      <ArrowUpOutlined /> 较昨日 +12%
                    </span>
                  }
                  formatter={(value) => `¥ ${value.toLocaleString()}`}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card variant={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
                <Statistic
                  title="今日订单"
                  value={8}
                  valueStyle={{ color: '#CD5C5C' }}
                  prefix={<UserAddOutlined style={{ color: '#CD5C5C' }} />}
                  suffix={
                    <span style={{ color: '#f5222d', fontSize: 12, marginLeft: 8 }}>
                      <ArrowDownOutlined /> 较昨日 -2
                    </span>
                  }
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card variant={false} style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}>
                <Statistic
                  title="新客户"
                  value={142}
                  valueStyle={{ color: '#22c55e' }}
                  prefix={<UserAddOutlined style={{ color: '#22c55e' }} />}
                  suffix={
                    <span style={{ color: '#f5222d', fontSize: 12, marginLeft: 8 }}>
                      <ArrowDownOutlined /> 较昨日 -2
                    </span>
                  }
                />
              </Card>
            </Col>
          </Row>

          {/* 2. 图表区域 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} lg={14}>
              <Card
                title="近7日收入趋势"
                variant={false}
                style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}
              >
                <div id="revenue-chart" style={{ height: 380, width: '100%' }} />
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card
                title="理疗项目占比"
                variant={false}
                style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)', display: 'flex', flexDirection: 'column' }}
              >
                <div id="service-chart" style={{ height: 260, width: '100%', margin: '0 auto' }} />
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, padding: '16px 0 8px' }}>
                  {[
                    { name: '推拿按摩', value: '35%', color: '#8B5A2B' },
                    { name: '针灸治疗', value: '25%', color: '#2F4F4F' },
                    { name: '艾灸养生', value: '20%', color: '#CD5C5C' },
                    { name: '拔罐疗法', value: '15%', color: '#22c55e' },
                    { name: '中药熏蒸', value: '5%', color: '#a855f7' }
                  ].map((item, index) => (
                    <div key={index} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{
                        width: 12,
                        height: 12,
                        borderRadius: '50%',
                        backgroundColor: item.color
                      }} />
                      <span style={{ fontSize: 14 }}>{item.name}：{item.value}</span>
                    </div>
                  ))}
                </div>
              </Card>
            </Col>
          </Row>

          {/* 3. 业务功能区 */}
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={16}>
              <Card
                title="今日预约"
                
                style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)' }}
              
              >
                <Table
                  columns={appointmentColumns}
                  dataSource={appointmentData}
                  pagination={{ pageSize: 6, showSizeChanger: false }}
                  rowHover
                  scroll={{ x: 'max-content' }}
                  style={{ marginTop: 8 }}
                />
              </Card>
            </Col>

            <Col xs={24} lg={8}>
              <Card
                title="快速操作"
                variant={false}
                style={{ boxShadow: '0 2px 8px rgba(0,0,0,0.08)', height: '100%' }}
              >
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, padding: 8 }}>
                  {quickActions.map((action, index) => (
                    <Button
                      key={index}
                      type="text"
                      style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        gap: 8,
                        padding: 12,
                        height: 80,
                        borderRadius: 8,
                        backgroundColor: `${action.color}10`,
                        color: action.color,
                        transition: 'backgroundColor 0.2s'
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.backgroundColor = `${action.color}20`}
                      onMouseLeave={(e) => e.currentTarget.style.backgroundColor = `${action.color}10`}
                      onClick={action.onClick} // 绑定对应点击方法
                    >
                      <span style={{ fontSize: 20 }}>{action.icon}</span>
                      <span style={{ fontSize: 14, fontWeight: 500 }}>{action.label}</span>
                    </Button>
                  ))}
                </div>
              </Card>
            </Col>
          </Row>


          {/* 新增产品模态框 */}
          <Modal
            style={{ top: "50px" }}
            title={<Title>{"新增产品"}</Title>}
            open={isAddProductModal}
            onCancel={() => setIsAddProductModal(false)}
            footer={[]}
            width={700}
            destroyOnHidden
          >
            <AddProduct />
          </Modal>
          {/* 设置排班模态框 */}
          <Modal
            style={{ top: "50px" }}
            open={isArrangeModal}
            onCancel={() => setIsArrangeModal(false)}
            footer={false}
            width={"900px"}
            destroyOnHidden
          >

            <AddArrange

            ></AddArrange>

          </Modal>

          {/* 新增员工模态框 */}
          <Modal
            title="新增员工"
            open={isAddEmployeeModal}
            onCancel={() => setIsAddEmployeeModal(false)}
            style={{ top: "50px" }}
            width={700}
            destroyOnHidden
            footer={null}
          >
            <AddEmployee></AddEmployee>
          </Modal>
        </div>


      )}

    </div>
  );
};

export default Home;